﻿Imports TransportadoraToledoBLL
Imports System.IO
Public Class frm_agendamento_carga
    Dim objA As AgendamentoBLL
    Dim objC As ClienteBLL
    Dim protocolo, tipo_carga As String
    Dim valor As Double
    Dim objCargas As CargasBLL
    Public controle As String
    Public ultimo, primeiro, atual, codigo As Integer
    Dim tab, tab2 As DataTable
    Dim cont As Integer = 0
    Dim dt As Date
#Region "Métodos"
    Public Sub carregaPropriedades()
        Try
            objA = New AgendamentoBLL
            If (tbCodigo.Text = "") Then
                objA.pAge_codigo = 0
            Else
                objA.pAge_codigo = tbCodigo.Text
            End If
            If (tbCodDestinatario.Text = "") Then
                objA.pCod_cli_destinatario = 0
            Else
                objA.pCod_cli_destinatario = tbCodDestinatario.Text
            End If
            If (tbCodRemetente.Text = "") Then
                objA.pCod_cli_remetente = 0
            Else
                objA.pCod_cli_remetente = tbCodRemetente.Text
            End If
            objA.pAge_data = dtAgendamento.Value.Date
            objA.pAge_dt_previsao = dtPrevEntrega.Value.Date
            objA.plCargas.Clear()
            For Each linha As DataRow In tab2.Rows
                Dim objCargas As New Cargas_AgendamentoBLL
                objCargas.pCar_codigo = linha("car_codigo")
                objA.plCargas.Add(objCargas)
                objCargas = Nothing
            Next
        Catch ex As Exception
            MessageBox.Show("Erro: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
    Public Function contaCargas(ByVal tipo As Char, inicio As Char) As Integer

        Try
            If (inicio = "S") Then
                For Each linha As DataRow In tab2.Rows
                    cont = cont + 1
                Next
            Else
                If (tipo = "A") Then
                    cont = cont + 1
                Else
                    cont = cont - 1
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        Return cont
    End Function
    Public Sub localizarClienteAgendamento()
        Try
            objA = New AgendamentoBLL
            objA.localizarClientesAgendamento(tbCodigo.Text)
            tbCodDestinatario.Text = objA.pCod_cli_destinatario
            objC = New ClienteBLL
            objC.localizar(objA.pCod_cli_destinatario)
            tbDestinatario.Text = objC.pNome
            tbCodRemetente.Text = objA.pCod_cli_remetente
            objC.localizar(objA.pCod_cli_remetente)
            tbNomeRemetente.Text = objC.pNome
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            objC = Nothing
        End Try
    End Sub
    Public Sub carregaCampos()
        Try
            tbCodigo.Text = objA.pAge_codigo
            dtAgendamento.Text = objA.pAge_data.Date
            dtPrevEntrega.Text = objA.pAge_dt_previsao.Date
            dgCargas.DataSource = tab2
            localizarClienteAgendamento()
        Catch ex As Exception
            MessageBox.Show("Erro", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
    Public Sub associaGrid()
        Try
            tab = New DataTable
            tab.Columns.Add("age_codigo", GetType(Integer))
            tab.Columns.Add("pes_codigo", GetType(Integer))
            tab.Columns.Add("pes_nome", GetType(String))
            tab.Columns.Add("pes_tipo_dr", GetType(Char))
            tab.Columns.Add("age_data", GetType(Date))
            dgConsulta.DataSource = tab
            dgConsulta.Columns("age_codigo").HeaderText = "Código"
            dgConsulta.Columns("age_codigo").Width = 90
            dgConsulta.Columns("pes_codigo").Visible = False
            dgConsulta.Columns("pes_nome").HeaderText = "Nome"
            dgConsulta.Columns("pes_nome").Width = 280
            dgConsulta.Columns("age_data").HeaderText = "Data"
            dgConsulta.Columns("age_data").Width = 120
            dgConsulta.Columns("pes_tipo_dr").HeaderText = "Tipo Cliente"
            dgConsulta.Columns("pes_tipo_dr").Width = 120
        Catch ex As Exception
            MessageBox.Show("Erro", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
    Public Sub associaGriCargas()
        Try
            tab2 = New DataTable
            tab2.Columns.Add("age_codigo", GetType(Integer))
            tab2.Columns.Add("car_codigo", GetType(Integer))
            tab2.Columns.Add("car_protocolo", GetType(String))
            tab2.Columns.Add("tc_descricao", GetType(String))
            tab2.Columns.Add("car_valor", GetType(Double))
            dgCargas.DataSource = tab2
            dgCargas.Columns("age_codigo").Visible = False
            dgCargas.Columns("car_codigo").HeaderText = "Código"
            dgCargas.Columns("car_protocolo").HeaderText = "Protocolo"
            dgCargas.Columns("tc_descricao").HeaderText = "Tipo Carga"
            dgCargas.Columns("car_valor").HeaderText = "Valor"
            dgCargas.Columns("car_codigo").Width = 70
            dgCargas.Columns("car_protocolo").Width = 100
            dgCargas.Columns("tc_descricao").Width = 100
            dgCargas.Columns("car_valor").Width = 100
        Catch ex As Exception
            MessageBox.Show("Erro", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
    Public Sub limpar()
        tbCodCarga.Text = ""
        tbCodDestinatario.Text = ""
        tbCodigo.Text = ""
        tbCodRemetente.Text = ""
        tbDestinatario.Text = ""
        tbNomeRemetente.Text = ""
        dtAgendamento.Value = Date.Now
        dtPrevEntrega.Value = Date.Now
        associaGriCargas()
        lqtdCargas.Text = 0
    End Sub
    Sub carregaPrimeiroUltimo()
        Try
            objA = New AgendamentoBLL
            ultimo = objA.localizarPrimeiroUltimo("ultimo")
            primeiro = objA.localizarPrimeiroUltimo("primeiro")
            atual = ultimo
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        objA = Nothing
    End Sub
    Sub carregaUltimo()
        Try
            If (ultimo <> 0) Then
                'algum usuario foi clicado
                objA = New AgendamentoBLL
                tab2 = objA.localizar(ultimo)
                If (objA.pAge_codigo <> 0) Then
                    carregaCampos()
                End If
            End If
            objA = Nothing
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Sub carregaPrimeiro()
        If (primeiro <> 0) Then
            'algum usuario foi clicado
            objA = New AgendamentoBLL
            tab2 = objA.localizar(primeiro)
            If (objA.pAge_codigo <> 0) Then
                carregaCampos()
            End If
        End If
        objA = Nothing
    End Sub
    Sub status(ByVal sta As Boolean)

        If (tbCodigo.Text = "" Or controle = "A") Then
            bIncluir.Enabled = sta
            If (tbCodigo.Text = "") Then
                bAlterar.Enabled = False
                bVaPara.Enabled = False
                bPesquisar.Enabled = False
                bExcluir.Enabled = False
                gbConsulta.Enabled = False
            Else
                bExcluir.Enabled = sta
                bPesquisar.Enabled = sta
                bAlterar.Enabled = sta
                bVaPara.Enabled = sta
            End If
            bCancelar.Enabled = Not sta
            bSalvar.Enabled = Not sta
            bPrimeiro.Enabled = sta
            bProximo.Enabled = sta
            bUltimo.Enabled = sta
            bAnterior.Enabled = sta
            gbConteudo.Enabled = Not sta

        Else
            bIncluir.Enabled = sta

            If (tbCodigo.Text = "") Then
                bExcluir.Enabled = False
                bAlterar.Enabled = False
                bVaPara.Enabled = False
                bPesquisar.Enabled = False
            Else
                bExcluir.Enabled = sta
                bAlterar.Enabled = sta
                bVaPara.Enabled = sta
                bPesquisar.Enabled = sta
            End If

            bCancelar.Enabled = Not sta
            bSalvar.Enabled = Not sta

            gbConteudo.Enabled = Not sta
        End If

        If (atual = primeiro And atual = ultimo) Then
            bProximo.Enabled = False
            bUltimo.Enabled = False
            bAnterior.Enabled = False
            bPrimeiro.Enabled = False
        ElseIf (atual = ultimo) Then
            bProximo.Enabled = False
            bUltimo.Enabled = False
            bAnterior.Enabled = True
            bPrimeiro.Enabled = True
        ElseIf (atual = primeiro) Then
            bProximo.Enabled = True
            bUltimo.Enabled = True
            bAnterior.Enabled = False
            bPrimeiro.Enabled = False
        Else
            bProximo.Enabled = True
            bUltimo.Enabled = True
            bAnterior.Enabled = True
            bPrimeiro.Enabled = True
        End If
    End Sub
#End Region

    Private Sub bIncluir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bIncluir.Click
        controle = "I"
        limpar()
        bDestinatario.Focus()
        status(False)
        dtPrevEntrega.Value = Date.Now.AddDays(10)
        cont = 0
    End Sub

    Private Sub bAlterar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bAlterar.Click
        Try
            objA = New AgendamentoBLL
            objA.VerificaExclusao(tbCodigo.Text)
            If (objA.pVerifica = False) Then
                controle = "A"
                status(False)
            Else
                MessageBox.Show("O Agendamento não pode ser alterado!" & Environment.NewLine &
                                    "Agendamento alocado em algum veiculo", "TransToledo", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        
    End Sub

    Private Sub bExcluir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bExcluir.Click
        Try
            If (MessageBox.Show("Deseja excluir?", "", MessageBoxButtons.YesNo) = DialogResult.Yes) Then
                objA = New AgendamentoBLL
                objA.VerificaExclusao(tbCodigo.Text)
                If (objA.pVerifica = False) Then
                    carregaPropriedades()
                    objA.excluir()
                    MessageBox.Show("Excluido com sucesso!")
                    limpar()
                    carregaPrimeiroUltimo()
                    carregaUltimo()
                    status(True)
                Else
                    MessageBox.Show("O Agendamento não pode ser excluido!" & Environment.NewLine &
                                    "Agendamento alocado em algum veiculo", "TransToledo", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub bSalvar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bSalvar.Click
        Try
            carregaPropriedades()
            If (controle = "I") Then
                objA.inserir()
                MessageBox.Show("Incluido com sucesso!", "TransToledo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
                limpar()
                carregaPrimeiroUltimo()
                carregaUltimo()
                status(True)
            Else
                objA.alterar()
                MessageBox.Show("Alterado com sucesso!", "TransToledo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
                status(True)
            End If
            cont = 0
            contaCargas("A", "S")
            lqtdCargas.Text = cont
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub bCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bCancelar.Click
        If (controle = "I" Or controle = "A") Then
            carregaPrimeiroUltimo()
            carregaUltimo()
            controle = "C"
        End If
        cont = 0
        contaCargas("A", "S")
        lqtdCargas.Text = cont
        controle = ""
        status(True)
        'dgCargas.DataSource = Nothing
        'associaGriCargas()
        'limpar()
    End Sub

    Private Sub bVaPara_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bVaPara.Click
        Try
            Dim frm As New frm_VaPara("agendamento")
            frm.ShowDialog()
            If (frm.codigo <> 0) Then
                'algum usuario foi clicado
                objA = New AgendamentoBLL
                objA.localizar(frm.codigo)
                If (objA.pAge_codigo <> 0) Then
                    carregaCampos()
                    atual = objA.pAge_codigo
                Else
                    MessageBox.Show("Registro Inexistente!", "TransToledo", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End If
            End If
            status(True)
            frm = Nothing
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            objA = Nothing
        End Try
    End Sub

    Private Sub bPesquisar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bPesquisar.Click
        gbConsulta.Enabled = True
        gbConsulta.Visible = True
        bPesquisar.Enabled = False
        Me.Location = New System.Drawing.Point(Me.Location.X, Me.Location.Y - 127)
        Me.Size = New Size(730, 620)
    End Sub

    Private Sub bPrimeiro_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bPrimeiro.Click
        carregaPrimeiro()
        atual = primeiro
        cont = 0
        contaCargas("A", "S")
        lqtdCargas.Text = cont
        status(True)
    End Sub

    Private Sub bAnterior_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bAnterior.Click
        Try
            objA = New AgendamentoBLL
            Dim codigo = objA.localizarProxAnteriro("anterior", atual)
            If (codigo <> 0) Then
                tab2 = objA.localizar(codigo)
                If (objA.pAge_codigo <> 0) Then
                    atual = objA.pAge_codigo
                    carregaCampos()
                    cont = 0
                    contaCargas("A", "S")
                    lqtdCargas.Text = cont
                End If
            End If
            status(True)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            objA = Nothing
        End Try
    End Sub

    Private Sub bProximo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bProximo.Click
        Try
            objA = New AgendamentoBLL
            Dim codigo = objA.localizarProxAnteriro("proximo", atual)
            If (codigo <> 0) Then
                tab2 = objA.localizar(codigo)
                If (objA.pAge_codigo <> 0) Then
                    atual = objA.pAge_codigo
                    carregaCampos()
                    cont = 0
                    contaCargas("A", "S")
                    lqtdCargas.Text = cont
                End If
            End If
            status(True)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            objA = Nothing
        End Try
    End Sub

    Private Sub bUltimo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bUltimo.Click
        carregaUltimo()
        atual = ultimo
        cont = 0
        contaCargas("A", "S")
        lqtdCargas.Text = cont
        status(True)
    End Sub

    Private Sub bAjuda_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bAjuda.Click
        Try
            Dim Ie As Object
            Ie = CreateObject("InternetExplorer.Application")
            Ie.Visible = True
            Ie.Navigate("D:\Aulas Faculdade\2012\6ºTermo\Projeto Integrado de Sistemas II\Trabalho\TransportadoraToledo\TransportadoraToledo\TransportadoraToledo\Arquivo de Ajuda\index.html")
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub bSair_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bSair.Click
        Me.Close()
    End Sub

    Private Sub frm_agendamento_carga_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            associaGriCargas()
            carregaPrimeiroUltimo()
            carregaUltimo()
            bCancelar_Click(sender, e)
            associaGrid()
            gbConsulta.Visible = False
            Me.Location = New System.Drawing.Point(Me.Location.X, Me.Location.Y + 127)
            Me.Size = New Size(723, 367)
            'carregaAbasVeiculo(codigo)
            'contaCargas("A", "S")
            lqtdCargas.Text = cont
            dt = dtAgendamento.Value.Date
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub bRemetente_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bRemetente.Click
        Try
            Dim frm As New frm_consultas
            objC = New ClienteBLL
            frm.tipo = "Clientes"
            frm.ShowDialog()
            If (frm.codigo <> 0) Then
                If (tbCodDestinatario.Text <> "") Then
                    If (tbCodDestinatario.Text = frm.codigo) Then
                        MessageBox.Show("O Destinatário não pode ser igual ao Remetente", "Transtoledo", MessageBoxButtons.OK, MessageBoxIcon.Error)
                        tbCodRemetente.Text = ""
                        tbNomeRemetente.Text = ""
                    Else
                        objC.localizar(frm.codigo)
                        tbCodRemetente.Text = objC.pCodigo
                        tbNomeRemetente.Text = objC.pNome
                    End If
                Else
                    objC.localizar(frm.codigo)
                    tbCodRemetente.Text = objC.pCodigo
                    tbNomeRemetente.Text = objC.pNome
                End If

            End If
            frm = Nothing
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Erro")
        Finally
            objC = Nothing
        End Try
    End Sub

    Private Sub bDestinatario_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bDestinatario.Click
        Try
            Dim frm As New frm_consultas
            objC = New ClienteBLL
            frm.tipo = "Clientes"
            frm.ShowDialog()
            If (frm.codigo <> 0) Then
                If (tbCodRemetente.Text <> "") Then
                    If (tbCodRemetente.Text = frm.codigo) Then
                        MessageBox.Show("O Destinatário não pode ser igual ao Remetente", "Transtoledo", MessageBoxButtons.OK, MessageBoxIcon.Error)
                        tbCodDestinatario.Text = ""
                        tbDestinatario.Text = ""
                    Else
                        objC.localizar(frm.codigo)
                        tbCodDestinatario.Text = objC.pCodigo
                        tbDestinatario.Text = objC.pNome
                    End If
                Else
                    objC.localizar(frm.codigo)
                    tbCodDestinatario.Text = objC.pCodigo
                    tbDestinatario.Text = objC.pNome
                End If
            End If
            frm = Nothing
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Erro")
        Finally
            objC = Nothing
        End Try
    End Sub

    Private Sub dtAgendamento_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtAgendamento.ValueChanged
        dtPrevEntrega.Value = dtAgendamento.Value.Date.AddDays(10)
    End Sub

    Private Sub bCargas_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bCargas.Click
        Try
            Dim frm As New frm_consultas
            objA = New AgendamentoBLL
            objCargas = New CargasBLL
            Dim tab As DataTable
            frm.tipo = "cargas"
            frm.ShowDialog()
            If (frm.codigo <> 0) Then
                If (objA.validaCarga(frm.protocolo)) Then
                    MessageBox.Show("A carga com o protocolo: " & objA.pCar_protocolo & " ja possui um agendamento: " & Environment.NewLine &
                                    "Remetente: " & objA.pPes_nome_remetente & Environment.NewLine &
                                    "Destinatario: " & objA.pPes_nome_destinatario & Environment.NewLine &
                                    "Na data: " & objA.pAge_data & Environment.NewLine &
                                    "Escolha outra carga", "TransToledo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Else
                    tab = objA.verificaStatus(frm.codigo)
                    If (tab.Rows.Count > 0) Then
                        MessageBox.Show("A carga não pode se adicionada" & Environment.NewLine &
                                        "A carga não está aguardando agendamento", "TransToledo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
                    Else
                        objCargas.localizar(frm.codigo)
                        objA.localizarTipoCarga(frm.codigo)
                        tipo_carga = objA.pTipo_carga
                        tbCodCarga.Text = objCargas.pCarCodigo
                        protocolo = objCargas.pProtocolo
                        valor = objCargas.pcarValor
                    End If
                End If
            End If
            frm = Nothing
            objA = Nothing
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub bAdicionar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bAdicionar.Click
        Try
            If (tbCodCarga.Text = "") Then
                MessageBox.Show("Escolha uma carga para adicionar", "TransToledo", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Else
                If (dgCargas.Rows.Count = 0) Then
                    Dim linha As DataRow
                    linha = tab2.NewRow()
                    linha("car_codigo") = tbCodCarga.Text
                    linha("car_protocolo") = protocolo
                    linha("tc_descricao") = tipo_carga
                    linha("car_valor") = valor
                    dgCargas.Columns("car_valor").DefaultCellStyle.Format = "R$ ###,###0.00"
                    tab2.Rows.Add(linha)
                    tab2.AcceptChanges()
                    tbCodCarga.Text = ""
                    protocolo = ""
                    valor = 0
                    Dim contador As Integer = contaCargas("A", "N")
                    lqtdCargas.Text = contador
                Else
                    Dim ret As Boolean = False
                    Dim cod As Integer = tbCodCarga.Text
                    For i As Integer = 0 To dgCargas.Rows.Count - 1 Step 1
                        If (dgCargas.Rows.Item(i).Cells("car_codigo").Value = cod) Then
                            MessageBox.Show("Essa carga ja está incluida", "TransToledo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                            tbCodCarga.Text = ""
                            ret = True
                        End If
                    Next
                    If (ret <> True) Then
                        Dim linha As DataRow
                        linha = tab2.NewRow()
                        linha("car_codigo") = tbCodCarga.Text
                        linha("car_protocolo") = protocolo
                        linha("tc_descricao") = tipo_carga
                        linha("car_valor") = valor
                        dgCargas.Columns("car_valor").DefaultCellStyle.Format = "R$ ###,###0.00"
                        tab2.Rows.Add(linha)
                        tab2.AcceptChanges()
                        tbCodCarga.Text = ""
                        protocolo = ""
                        valor = 0
                        Dim contador As Integer = contaCargas("A", "N")
                        lqtdCargas.Text = contador
                    End If
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub bExcluirCarga_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bExcluirCarga.Click
        Dim i As Integer
        i = 0
        Try
            For Each linha As DataGridViewRow In dgCargas.SelectedRows
                i = linha.Index
            Next
            If (i >= 0) Then
                tab2.Rows.RemoveAt(i)
                tab2.AcceptChanges()
                Dim contador As Integer = contaCargas("R", "N")
                lqtdCargas.Text = contador
            Else
                MessageBox.Show("Não existem itens para ser excluido!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If
        Catch ex As Exception
            MessageBox.Show("Não existem itens para ser excluido!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub bFiltroDescricao_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bFiltroDescricao.Click
        Dim tipo As Char
        Dim tab As DataTable
        Try
            If (cbTipo.SelectedIndex = 1) Then
                tipo = "D"
            ElseIf (cbTipo.SelectedIndex = 2) Then
                tipo = "R"
            Else
                MessageBox.Show("Escolha um tipo")
            End If
            objA = New AgendamentoBLL
            tab = objA.localizar(txtConsultar.Text, tipo)
            dgConsulta.DataSource = tab
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        objA = Nothing
    End Sub
    Private Sub bClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bClose.Click
        gbConsulta.Visible = False
        Me.Location = New System.Drawing.Point(Me.Location.X, Me.Location.Y + 127)
        Me.Size = New Size(723, 367)
        bPesquisar.Enabled = True
    End Sub

    Private Sub dgConsulta_CellDoubleClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgConsulta.CellDoubleClick
        Dim codigo As Integer
        Try
            If (e.RowIndex >= 0) Then
                codigo = dgConsulta.Rows(e.RowIndex).Cells("age_codigo").Value
                objA = New AgendamentoBLL
                objA.localizar(codigo)
                If (objA.pAge_codigo <> 0) Then
                    atual = objA.pAge_codigo
                    carregaCampos()
                    gbConsulta.Visible = False
                    Me.Location = New System.Drawing.Point(Me.Location.X, Me.Location.Y + 127)
                    Me.Size = New Size(723, 367)
                    bPesquisar.Enabled = True
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            objA = Nothing
        End Try
    End Sub

    Private Sub tbCodCarga_Leave(sender As System.Object, e As System.EventArgs) Handles tbCodCarga.Leave
        Dim tab As DataTable
        Try
            objCargas = New CargasBLL
            objA = New AgendamentoBLL
            If (tbCodCarga.Text <> "") Then
                tab = objCargas.localizar(tbCodCarga.Text)
                If (tab.Rows.Count = 1) Then
                    If (objA.validaCarga(objCargas.pProtocolo)) Then
                        MessageBox.Show("A carga com o protocolo: " & objA.pCar_protocolo & " ja possui um agendamento: " & Environment.NewLine &
                                    "Remetente: " & objA.pPes_nome_remetente & Environment.NewLine &
                                    "Destinatario: " & objA.pPes_nome_destinatario & Environment.NewLine &
                                    "Na data: " & objA.pAge_data & Environment.NewLine &
                                    "Escolha outra carga", "TransToledo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    Else
                        tab = objA.verificaStatus(tbCodCarga.Text)
                        If (tab.Rows.Count > 0) Then
                            MessageBox.Show("A carga não pode se adicionada" & Environment.NewLine &
                                        "A carga não está aguardando agendamento", "TransToledo", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
                        Else
                            tbCodCarga.Text = objCargas.pCarCodigo
                            objA.localizarTipoCarga(objCargas.pCarCodigo)
                            tipo_carga = objA.pTipo_carga
                            protocolo = objCargas.pProtocolo
                            valor = objCargas.pcarValor
                            bAdicionar_Click(sender, e)
                        End If
                    End If
                Else
                    If (MessageBox.Show("Carga não cadastrada!" & Environment.NewLine &
                                    "Deseja cadastrar uma nova carga agora?", "TransToledo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes) Then
                        Dim frm As New frm_cadastro_cargas
                        frm.ShowDialog()
                        frm = Nothing
                    End If
                End If
            End If
            objCargas = Nothing
            tbCodCarga.Text = ""
            tbCodCarga.Focus()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub tbCodCarga_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles tbCodCarga.KeyPress
        Try
            If Not Char.IsNumber(e.KeyChar) And e.KeyChar <> Convert.ToChar(Keys.Back) Then
                e.Handled = True
            End If
            If (e.KeyChar = Convert.ToChar(Keys.Enter)) Then
                tbCodCarga_Leave(sender, e)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub dtPrevEntrega_ValueChanged(sender As System.Object, e As System.EventArgs) Handles dtPrevEntrega.ValueChanged
        Try
            If (dtPrevEntrega.Value < dtAgendamento.Value) Then
                MessageBox.Show("A data de previsão de entrega não pode ser menor que a data do agendamento")
                dtPrevEntrega.Value = Date.Now.AddDays(10)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
End Class
